package com.socool.sinofaith.ui;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.IntentFilter;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.socool.sinafaith.zbar.ZBarMainActivity;
import com.socool.sinofaith.R;
import com.socool.sinofaith.SocoolApplication;
import com.socool.sinofaith.jsonparse.HttpJsonAdapter;
import com.socool.sinofaith.model.AppUserInfo;
import com.socool.sinofaith.model.LoginMessage;
import com.socool.sinofaith.model.NewVersionBean;
import com.socool.sinofaith.service.PushMessageService;
import com.socool.sinofaith.util.AndroidSQLiteOpenHelper;
import com.socool.sinofaith.util.BGSharedPreference;
import com.socool.sinofaith.util.ConstansJsonUrl;
import com.socool.sinofaith.util.SinofaithUtil;
import com.socool.sinofaith.view.LoadingDialog;
import com.socool.sinofaith.view.MyDialog;

public class LoginActivity extends Activity implements View.OnClickListener {

	private EditText usernameEditText, passwordEditText;
	private Button submitButton, offlineLoginButton;
	private TextView forgetpasswd;
	private CheckBox remember;
	private LoadingDialog mLoadingDialog;
	private RequestQueue mQueue;

	public static final String DOWNLOAD_FOLDER_NAME = "Sinofaith";
	public static final String DOWNLOAD_FILE_NAME = "Sinofaith.apk";
	public static final String KEY_NAME_DOWNLOAD_ID = "downloadId";

	Dialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login);
		Log.i("jsc", "heheh");
		mQueue = Volley.newRequestQueue(this);
		SocoolApplication.addActivity(this);
		String aa = (String) BGSharedPreference.get(LoginActivity.this, "Login_Result_Content", "");
		Log.i("jsc", "aa" + aa);

		// init();

	}

	void init() {
		mLoadingDialog = new LoadingDialog(this);
		usernameEditText = (EditText) findViewById(R.id.usernameEditText);
		passwordEditText = (EditText) findViewById(R.id.passwordEditText);
		remember = (CheckBox) findViewById(R.id.remember);

		SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
		usernameEditText.setText(preferences.getString("userName", ""));
		passwordEditText.setText(preferences.getString("password", ""));
		remember.setChecked(preferences.getBoolean("remember", false));

		submitButton = (Button) findViewById(R.id.submitButton);
		offlineLoginButton = (Button) findViewById(R.id.offlineLoginButton);
		forgetpasswd = (TextView) findViewById(R.id.forgetpasswd);
		submitButton.setOnClickListener(this);
		forgetpasswd.setOnClickListener(this);
		offlineLoginButton.setOnClickListener(this);
		SinofaithUtil.startPushService(this, 15 * 60, PushMessageService.class, PushMessageService.ACTION);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {

		case R.id.submitButton:

			if (isReadyToLogin()) {
				// FinalHttp fh = new FinalHttp();
				// AjaxParams params = new AjaxParams();
				// params.put("sid", ConstansJsonUrl.login_url);
				// params.put("did", SinofaithUtil.did);
				// params.put("ucode",
				// SinofaithUtil.getDeviceID(LoginActivity.this));
				// params.put("Mobile", usernameEditText.getText().toString());
				// params.put("Pwd",
				// SinofaithUtil.md5(passwordEditText.getText()
				// .toString()));
				//
				// Log.i("TAG", params+"");
				// Log.v("qqqq", SinofaithUtil.md5(passwordEditText.getText()
				// .toString()));
				// fh.get(ConstansJsonUrl.REQUEST_URL, params, new
				// AjaxCallBack() {
				//
				// @Override
				// public void onStart() {
				// // TODO Auto-generated method stub
				// super.onStart();
				// mLoadingDialog.show();
				// }
				//
				// @Override
				// public void onLoading(long count, long current) {
				// // TODO Auto-generated method stub
				// super.onLoading(count, current);
				// }
				//
				// @Override
				// public void onSuccess(Object t) {
				// // TODO Auto-generated method stub
				// super.onSuccess(t);
				// mLoadingDialog.dismiss();
				// Log.v("qqqq", t.toString());
				// try {
				// LoginMessage loginMessage = HttpJsonAdapter
				// .getInstance().get(t.toString(),
				// LoginMessage.class);
				// if (loginMessage.getResult().equals("0")) {
				//
				// SharedPreferences preferences = getSharedPreferences(
				// "login", MODE_PRIVATE);
				// Editor editor = preferences.edit();
				// if (remember.isChecked()) {
				// editor.putString("userName",
				// usernameEditText.getText()
				// .toString());
				// editor.putString("password",
				// passwordEditText.getText()
				// .toString());
				// editor.putBoolean("remember", true);
				// } else {
				// editor.putString("userName",
				// usernameEditText.getText()
				// .toString());
				// editor.putString("password", "");
				// editor.putBoolean("remember", false);
				// }
				// editor.commit();
				// ((SocoolApplication) LoginActivity.this
				// .getApplication())
				// .setOffLineLogin(false);
				// SinofaithUtil.userInfo = loginMessage
				// .getAppUserInfo().get(0);
				// Intent intent = new Intent(LoginActivity.this,
				// MainActivity.class);
				// LoginActivity.this.startActivity(intent);
				// LoginActivity.this.finish();
				//
				// } else {
				// Log.i("TAG", loginMessage.getDesc()+" else ");
				// Toast.makeText(LoginActivity.this,
				// loginMessage.getDesc(),
				// Toast.LENGTH_LONG).show();
				//
				// }
				// } catch (Exception e) {
				// Toast.makeText(LoginActivity.this, e.getMessage(),
				// Toast.LENGTH_LONG).show();
				// }
				//
				// }
				//
				// @Override
				// public void onFailure(Throwable t, int errorNo,
				// String strMsg) {
				// // TODO Auto-generated method stub
				// super.onFailure(t, errorNo, strMsg);
				// mLoadingDialog.dismiss();
				// Log.i("TAG", strMsg+" onfailure");
				// Toast.makeText(LoginActivity.this, strMsg,
				// Toast.LENGTH_LONG).show();
				// }
				//
				// });
				login();
			}
			break;

		case R.id.forgetpasswd:
			Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
			LoginActivity.this.startActivity(intent);
			break;

		case R.id.offlineLoginButton:
			if (isReadyToOffLineLogin()) {
				((SocoolApplication) LoginActivity.this.getApplication()).setOffLineLogin(true);
				SinofaithUtil.userInfo.setUserMobile(usernameEditText.getText().toString());
				SharedPreferences sp = this.getSharedPreferences("login", Context.MODE_PRIVATE);
				Editor edit = sp.edit();
				edit.putString("UserMobile", usernameEditText.getText().toString());
				edit.commit();
				edit = null;
				Intent offLineintent = new Intent(LoginActivity.this, MainActivity.class);
				LoginActivity.this.startActivity(offLineintent);
				LoginActivity.this.finish();
			}
			break;

		}

	}

	Boolean isReadyToLogin() {

		if (TextUtils.isEmpty(usernameEditText.getText())) {
			Toast.makeText(this, "请输入您的手机号码！", Toast.LENGTH_SHORT).show();
			return false;
		}
		String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
		if (!usernameEditText.getText().toString().matches(telRegex)) {
			Toast.makeText(this, "请输入正确的手机号码！！", Toast.LENGTH_SHORT).show();
			return false;
		}
		if (TextUtils.isEmpty(passwordEditText.getText())) {

			Toast.makeText(LoginActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	Boolean isReadyToOffLineLogin() {

		if (TextUtils.isEmpty(usernameEditText.getText())) {
			Toast.makeText(this, "请输入您的手机号码！", Toast.LENGTH_SHORT).show();
			return false;
		}
		String telRegex = "[1][3578]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
		if (!usernameEditText.getText().toString().matches(telRegex)) {
			Toast.makeText(this, "请输入正确的手机号码！！", Toast.LENGTH_SHORT).show();
			return false;
		}
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			// 具体的操作代码
			MyDialog.Builder builder = new MyDialog.Builder(this);
			builder.setTitle("确定要退出吗？").setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					// LoginActivity.this.finish();//
					// 结束当前Activity
					android.os.Process.killProcess(android.os.Process.myPid());
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.addCategory(Intent.CATEGORY_HOME);
					startActivity(intent);
					// System.exit(0);
				}
			}).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			Dialog dialog111 = builder.create();
			dialog111.show();
		}

		return super.onKeyDown(keyCode, event);
	}

	void checknet() {

		ArrayList<Activity> list = SocoolApplication.list;
		for (Activity activity : list) {
			if (null != activity) {
				if (activity != this) {
					activity.finish();
				}
			}
		}

		if (!checkNetworkInfo()) {
			/**
			 * MyDialog.Builder builder = new
			 * MyDialog.Builder(LoginActivity.this);
			 * builder.setTitle("很抱歉，当前您的网络请求超时") .setPositiveButton( "设置网络",
			 * new android.content.DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int which)
			 *           { startActivity(new Intent(
			 *           Settings.ACTION_WIRELESS_SETTINGS)); } })
			 *           .setNeutralButton("重试", new
			 *           DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int which)
			 *           { // TODO Auto-generated method stub checknet(); } })
			 *           .setNegativeButton( "取消", new
			 *           android.content.DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int which)
			 *           { dialog.dismiss(); // 结束当前Activity android.os.Process
			 *           .killProcess(android.os.Process .myPid()); Intent
			 *           intent = new Intent( Intent.ACTION_MAIN);
			 *           intent.addCategory(Intent.CATEGORY_HOME);
			 *           startActivity(intent); } }); dialog = builder.create();
			 *           dialog.setCanceledOnTouchOutside(false); dialog.show();
			 * 
			 */

		} else {
			checkUpdate();
		}

	}

	/**
	 * 检查网络状态
	 */
	private boolean checkNetworkInfo() {
		if (null != dialog && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}
		ConnectivityManager conMan = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		// mobile 3G Data Network
		State mobile = conMan.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
		// wifi
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
		// 如果3G网络和wifi网络都未连接，且不是处于正在连接状态 则进入Network Setting界面 由用户配置网络连接

		if (mobile == State.CONNECTED || mobile == State.CONNECTING) {
			return true;
		} else if (wifi == State.CONNECTED || wifi == State.CONNECTING) {
			return true;
		} else {
			return false;
		}

	}

	@SuppressLint("NewApi")
	@SuppressWarnings({ "unchecked", "rawtypes" })
	void checkUpdate() {
		FinalHttp fh = new FinalHttp();
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.getVersion_url);
		params.put("VerNum", getVersion());
		params.put("OS", SinofaithUtil.OS);
		params.put("Platform", SinofaithUtil.did);
		params.put("did", SinofaithUtil.did);
		fh.get(ConstansJsonUrl.REQUEST_URL, params, new AjaxCallBack() {
			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
				mLoadingDialog.show();
			}

			@Override
			public void onLoading(long count, long current) {
				// TODO Auto-generated method stub
				super.onLoading(count, current);
			}

			@Override
			public void onSuccess(Object t) {
				// TODO Auto-generated method stub
				super.onSuccess(t);
				mLoadingDialog.dismiss();
				try {
					final NewVersionBean newVersionBean = HttpJsonAdapter.getInstance().get(t.toString(),
							NewVersionBean.class);
					Log.i("jsc", "登录异常：" + newVersionBean.toString());
					if ("0".equals(newVersionBean.getResult())) {
						MyDialog.Builder builder = new MyDialog.Builder(LoginActivity.this);
						builder.setTitle("是否立即更新？");
						builder.setMessage(Html
								.fromHtml("版本号：V" + newVersionBean.getNewVersion().get(0).getSoftVerNumber()
										+ "<br/>更新说明：<br/>" + newVersionBean.getNewVersion().get(0).getSoftVerIntro())
								.toString());
						builder.setPositiveButton("立即更新", new android.content.DialogInterface.OnClickListener() {
							@SuppressLint("NewApi")
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
								// mLoadingDialog.show();
								// // // 显示下载对话框
								// DownloadManager downloadManager =
								// (DownloadManager)
								// getSystemService(DOWNLOAD_SERVICE);
								String apkUrl = ConstansJsonUrl.BASEURL + "/"
										+ newVersionBean.getNewVersion().get(0).getDownloadPath();
								Log.i("TAG", apkUrl);
								// DownloadManager.Request request = new
								// DownloadManager.Request(
								// Uri.parse(apkUrl));
								// File f=new File(new StringBuilder(Environment
								// .getExternalStorageDirectory().getAbsolutePath())
								// .append(File.separator)
								// .append(DOWNLOAD_FOLDER_NAME)
								// .append(File.separator).append(DOWNLOAD_FILE_NAME)
								// .toString());
								// if(f.exists()){
								// f.delete();
								// }
								// request.setDestinationInExternalPublicDir(
								// DOWNLOAD_FOLDER_NAME,
								// DOWNLOAD_FILE_NAME);
								// long downloadId = downloadManager
								// .enqueue(request);
								// SinofaithUtil.putLong(
								// LoginActivity.this,
								// KEY_NAME_DOWNLOAD_ID,
								// downloadId);
								Intent intent = new Intent();
								intent.setAction("android.intent.action.VIEW");
								Uri content_url = Uri.parse(apkUrl);
								intent.setData(content_url);
								startActivity(intent);
							}
						});
						if (newVersionBean.getNewVersion().get(0).getForceUpdate().equals("1")) {
							builder.setNegativeButton("稍后更新", new android.content.DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
									mLoadingDialog.dismiss();
								}
							});
						}
						dialog = builder.create();
						dialog.setCanceledOnTouchOutside(false);
						dialog.show();
					}
				} catch (Exception e) {
					e.printStackTrace();
					Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
				mLoadingDialog.dismiss();
				Toast.makeText(LoginActivity.this, strMsg, Toast.LENGTH_LONG).show();
			}
		});
	}

	/**
	 * 获取版本号
	 * 
	 * @return 当前应用的版本号
	 */
	public String getVersion() {
		try {
			PackageManager manager = this.getPackageManager();
			PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
			String version = info.versionName;
			return version;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	// 接受下载完成后的intent
	@SuppressLint("NewApi")
	class DownloadCompleteReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
				long downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);
				long downloadId = SinofaithUtil.getLong(context, KEY_NAME_DOWNLOAD_ID);
				if (downloadId == downId) {
					queryDownloadStatus(context, downloadId);
				}

			}
		}

		private void queryDownloadStatus(Context context, long downloadId) {
			DownloadManager downloadManager = (DownloadManager) context.getSystemService(DOWNLOAD_SERVICE);
			DownloadManager.Query query = new DownloadManager.Query();
			query.setFilterById(downloadId);
			Cursor c = downloadManager.query(query);
			if (c.moveToFirst()) {
				int status = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
				switch (status) {
				case DownloadManager.STATUS_PAUSED:
					Log.v("down", "STATUS_PAUSED");
				case DownloadManager.STATUS_PENDING:
					Log.v("down", "STATUS_PENDING");
				case DownloadManager.STATUS_RUNNING:
					// 正在下载，不做任何事情
					Log.v("down", "STATUS_RUNNING");
					break;
				case DownloadManager.STATUS_SUCCESSFUL:
					// 完成
					Log.v("down", "下载完成");
					mLoadingDialog.dismiss();
					String apkFilePath = new StringBuilder(Environment.getExternalStorageDirectory().getAbsolutePath())
							.append(File.separator).append(DOWNLOAD_FOLDER_NAME).append(File.separator)
							.append(DOWNLOAD_FILE_NAME).toString();
					SinofaithUtil.install(context, apkFilePath);
					break;
				case DownloadManager.STATUS_FAILED:
					// 清除已下载的内容，重新下载
					Log.v("down", "STATUS_FAILED");
					downloadManager.remove(downloadId);
					break;
				}
			}
		}
	}

	DownloadCompleteReceiver receiver = new DownloadCompleteReceiver();

	@SuppressLint("InlinedApi")
	@Override
	protected void onResume() {
		init();
		try {
			checknet();

		} catch (Exception e) {
			e.printStackTrace();
		}

		registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
		checkLogin();
		super.onResume();
	}

	private void checkLogin() {
		Log.i("jsc", "checkLogin()");
		String result = (String) BGSharedPreference.get(this, "Login_Result", "0");
		long nd = 1000 * 24 * 60 * 60;
		long nh = 1000 * 60 * 60;
		long nm = 1000 * 60;
		if (!result.equals("0")) {
			try {
				long savetime = Long.parseLong(result);
				long currentTime = System.currentTimeMillis();
				// 获得两个时间的毫秒时间差异
				long diff = savetime - currentTime;
				// 计算差多少小时
				long hour = diff % nd / nh;
				Log.i("jsc", "出差：" + hour);
				if (hour < 2) {// 是否小于两个小时
					Log.i("jsc", "在两小时之内");
					String response = (String) BGSharedPreference.get(LoginActivity.this, "Login_Result_Content", "");
					Log.i("jsc", "response:" + response);
					LoginMessage loginMessage = HttpJsonAdapter.getInstance().get(response, LoginMessage.class);
					((SocoolApplication) LoginActivity.this.getApplication()).setOffLineLogin(false);
					SinofaithUtil.userInfo = loginMessage.getAppUserInfo().get(0);
					Intent intent = new Intent(LoginActivity.this, MainActivity.class);
					LoginActivity.this.startActivity(intent);
					LoginActivity.this.finish();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			BGSharedPreference.put(LoginActivity.this, "Login_Result", "0");
		}

	}

	@Override
	protected void onDestroy() {
		if (receiver != null)
			unregisterReceiver(receiver);
		super.onDestroy();
	}

	private void login() {
		Log.i("jsc", "login()");
		AjaxParams params = new AjaxParams();
		params.put("sid", ConstansJsonUrl.login_url);
		params.put("did", SinofaithUtil.did);
		params.put("ucode", SinofaithUtil.getDeviceID(LoginActivity.this));
		params.put("Mobile", usernameEditText.getText().toString());
		params.put("Pwd", SinofaithUtil.md5(passwordEditText.getText().toString()));

		mLoadingDialog.show();
		JsonObjectRequest request = new JsonObjectRequest(Method.GET, ConstansJsonUrl.REQUEST_URL + "?" + params, null,
				new Response.Listener<JSONObject>() {

					@Override
					public void onResponse(JSONObject response) {
						mLoadingDialog.dismiss();
						Log.i("jsc", response + "");
						String number = null;
						try {
							
							BGSharedPreference.put(LoginActivity.this, "Login_Result_Content", response.toString());
							LoginMessage loginMessage = HttpJsonAdapter.getInstance().get(response.toString(),
									LoginMessage.class);
							if(loginMessage!=null&&loginMessage.getAppUserInfo()!=null&&loginMessage.getAppUserInfo().size()>0){
								number = loginMessage.getAppUserInfo().get(0).getUserMobile();
								
							}
						
							if (TextUtils.isEmpty(number)) {
								number = "";
							}
							
							Log.i("jsc", "结果：" + loginMessage.getResult() + "-number:" + number);
							if (loginMessage.getResult().equals("3") || number.equals("13400000001")) {
								Date date = new Date();
								Log.i("jsc", "存时间：" + date.getTime());
								BGSharedPreference.put(LoginActivity.this, "Login_Result",
										String.valueOf(date.getTime()));
								SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
								Editor editor = preferences.edit();

								if (remember.isChecked()) {
									editor.putString("userName", usernameEditText.getText().toString());
									editor.putString("password", passwordEditText.getText().toString());
									editor.putBoolean("remember", true);
								} else {
									editor.putString("userName", usernameEditText.getText().toString());
									editor.putString("password", "");
									editor.putBoolean("remember", false);
								}

								editor.putString("UserMobile", loginMessage.getAppUserInfo().get(0).getUserMobile());
								editor.commit();
								((SocoolApplication) LoginActivity.this.getApplication()).setOffLineLogin(false);
								SinofaithUtil.userInfo = loginMessage.getAppUserInfo().get(0);
								Intent intent = new Intent(LoginActivity.this, MainActivity.class);
								LoginActivity.this.startActivity(intent);
								LoginActivity.this.finish();

							} else if (loginMessage.getResult().equals("0")) {

								SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
								Editor editor = preferences.edit();

								if (remember.isChecked()) {
									editor.putString("userName", usernameEditText.getText().toString());
									editor.putString("password", passwordEditText.getText().toString());
									editor.putBoolean("remember", true);
								} else {
									editor.putString("userName", usernameEditText.getText().toString());
									editor.putString("password", "");
									editor.putBoolean("remember", false);
								}

								editor.putString("UserMobile", loginMessage.getAppUserInfo().get(0).getUserMobile());
								editor.commit();
								((SocoolApplication) LoginActivity.this.getApplication()).setOffLineLogin(false);
								SinofaithUtil.userInfo = loginMessage.getAppUserInfo().get(0);
								Intent intent = new Intent(LoginActivity.this, MainActivity.class);
								LoginActivity.this.startActivity(intent);
								LoginActivity.this.finish();

							} else {
								Log.i("TAG", loginMessage.getDesc() + " else ");
								Toast.makeText(LoginActivity.this, loginMessage.getDesc(), Toast.LENGTH_LONG).show();

							}
						} catch (Exception e) {
							e.printStackTrace();
							Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						mLoadingDialog.dismiss();
						Log.i("TAG", " onfailure" + error.networkResponse);
						Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_LONG).show();
					}

				});
		request.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, 1, 1.0f));
		mQueue.add(request);

	}
}
